package real.bytedance.jdk;
import java.util.*;

//模拟生产者消费者模型
public class ConsumerAndProductor {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        Consumer consumer = new Consumer(queue);
        Productor productor = new Productor(queue);

        consumer.start();
        productor.start();
    }
}

class Consumer extends Thread {

    private static int MIN_SIZE = 0;
    private Queue<Integer> shareQueue;

    public Consumer(Queue<Integer> shareQueue) {
        super();
        this.shareQueue = shareQueue;
    }

    @Override
    public void run() {
        consumer();
    }

    public void consumer() {
        for (int i = 0; i < 100; i++) {
            synchronized (shareQueue) {
                while (shareQueue.size() <= MIN_SIZE) {
                    //队列不足，等待生产
                    try {
                        shareQueue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                   
                }
                System.out.print( "cur size: " + shareQueue.size() + ", ");
                System.out.println("consume: " + shareQueue.poll());
            }
        }
    }
}

class Productor extends Thread {
    private static int MAX_SIZE = 100;
    private Queue<Integer> shareQueue;

    public Productor(Queue<Integer> shareQueue) {
        super();
        this.shareQueue = shareQueue;
    }

    @Override
    public void run() {
        product();
    }
    public void product() {
        for (int i = 0; i < 100; i++) {
            synchronized(shareQueue) {
                while (shareQueue.size() >= MAX_SIZE) {
                    try {
                        shareQueue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }                   
                }

                shareQueue.add(i);
                System.out.println("I have product a production, cur size:" + shareQueue.size());
                shareQueue.notify();
            }
        }
    }
}
